/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.admin.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.UserTreeDto;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.UserService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.yami.shop.common.response.ServerResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author lgh on 2018/10/16.
 */
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:user:page')")
    public ServerResponseEntity<IPage<User>> page(User user,PageParam<User> page) {
        IPage<User> userPage = userService.page(page, new LambdaQueryWrapper<User>()
                .like(StrUtil.isNotBlank(user.getNickName()), User::getNickName, user.getNickName())
                .eq(user.getStatus() != null, User::getStatus, user.getStatus()));
        for (User userResult : userPage.getRecords()) {
            userResult.setNickName(userResult.getNickName() == null ? "" : userResult.getNickName());
        }
        return ServerResponseEntity.success(userPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{userId}")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<User> info(@PathVariable("userId") String userId) {
        User user = userService.getById(userId);
        user.setNickName(user.getNickName() == null ? "" : user.getNickName());
        return ServerResponseEntity.success(user);
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:user:update')")
    public ServerResponseEntity<Void> update(@RequestBody User user) {
        user.setModifyTime(new Date());
        //user.setNickName(user.getNickName() == null ? "" : user.getNickName());
        userService.updateById(user);

        if(user.getVipLevel() != null){
            if(user.getVipLevel() == 3){
                //设置用户为分部 时 推荐人设置为空
                userService.lambdaUpdate().set(User::getHigherLevelUid,null).eq(User::getUserId,user.getUserId()).update();
            }
        }

        return ServerResponseEntity.success();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('admin:user:delete')")
    public ServerResponseEntity<Void> delete(@RequestBody String[] userIds) {
        userService.removeByIds(Arrays.asList(userIds));
        return ServerResponseEntity.success();
    }

    /**
     * 获取下级用户,展示树形图(三级分销功能接口)
     */
    @GetMapping("/getLowerLevel/{userId}")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<List<UserTreeDto>> getLowerLevel(@PathVariable("userId") String userId) {
        List<UserTreeDto> lsit1=new ArrayList<>();
        List<User> lsit0=new ArrayList<>();

        //根用户
        User user = userService.getById(userId);
        lsit0.add(user);

        //下1级
        List<User> list = userService.lambdaQuery().eq(User::getHigherLevelUid, user.getUserId()).list();
        lsit0.addAll(list);

        //下2级
        List<String> collect = list.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        if(collect.isEmpty()){
            collect.add("-1");
        }
        List<User> list1 = userService.lambdaQuery().in(User::getHigherLevelUid, collect).list();
        lsit0.addAll(list1);

        //下3级
        List<String> collect1 = list1.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        if(collect1.isEmpty()){
            collect1.add("-1");
        }
        List<User> list2 = userService.lambdaQuery().in(User::getHigherLevelUid, collect1).list();
        lsit0.addAll(list2);


        for(User user1:lsit0){
            UserTreeDto dto=new UserTreeDto();
            dto.setId(user1.getUserId());
            dto.setPid(user1.getHigherLevelUid());
            dto.setName(user1.getNickName());
            dto.setImage_url(user1.getPic());

            lsit1.add(dto);
        }

        Map<String, List<UserTreeDto>> collect2 = lsit1.stream().filter((m) -> !StringUtil.equals(m.getId(), user.getUserId())).collect(Collectors.groupingBy(m -> m.getPid()));
        lsit1.forEach(m -> m.setChildren(collect2.get(m.getId())));


        List<UserTreeDto> collect3 = lsit1.stream().filter((m) -> StringUtil.equals(m.getId(), user.getUserId())).collect(Collectors.toList());

        return ServerResponseEntity.success(collect3);
    }

    /**
     * 搜索推荐人(三级分销功能接口)
     * @param queryType
     * @param queryKey
     * @return
     */
    @GetMapping("/getUserListByNickNameOrRealName")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<List<Map<String,String>>> getUserListByNickNameOrRealName(String queryType,String queryKey) {
        if(StringUtil.isBlank(queryType)){
            return ServerResponseEntity.showFailMsg("参数 queryType 不能为空");
        }
        if(StringUtil.isBlank(queryKey)){
            return ServerResponseEntity.showFailMsg("参数 queryKey 不能为空");
        }


        List<User> list = userService.lambdaQuery().select(User::getUserId, User::getNickName, User::getRealName).like(StringUtil.equals(queryType, "0"), User::getNickName, queryKey)
                .like(StringUtil.equals(queryType, "1"), User::getRealName, queryKey).list();

        List<Map<String,String>> list1=new ArrayList<>();

        for(User user:list){
            Map<String,String> map=new HashMap<>();
            map.put("id",user.getUserId());
            map.put("name",user.getNickName()+"("+user.getRealName()+")");

            list1.add(map);
        }
        return ServerResponseEntity.success(list1);
    }

    /**
     * 获取信息(三级分销功能接口)
     */
    @GetMapping("/getAllHigherLevelUser/{userId}")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<List<Map<String,String>>> getAllHigherLevelUser(@PathVariable("userId") String userId) {
        List<User> list=userService.getAllHigherLevelUser(userId);
        List<Map<String,String>> ramp=new ArrayList<>();

        for (User user:list){
            Map<String,String> map=new HashMap<>();
            map.put("id",user.getUserId());
            map.put("nickName",user.getNickName());
            map.put("realName",user.getRealName());
            ramp.add(map);
        }
        return ServerResponseEntity.success(ramp);
    }

    /**
     * 查询符合条件的所有用户(三级分销功能接口)
     * @param user
     * @return
     */
    @GetMapping("/getAll")
    @PreAuthorize("@pms.hasPermission('admin:user:page')")
    public ServerResponseEntity<List<User>> getAll(User user) {
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>(user)
                .like(StrUtil.isNotBlank(user.getNickName()), User::getNickName, user.getNickName());

        List<User> list = userService.list(eq);
        for (User userResult : list) {
            userResult.setNickName(userResult.getNickName() == null ? "" : userResult.getNickName());
            userResult.setPayPassword("");
            userResult.setLoginPassword("");
        }
        return ServerResponseEntity.success(list);
    }


    /**
     * 获取下级用户,展示树形图(三级分销功能接口)
     */
    @GetMapping("/getLowerLevelBySharedUid/{userId}")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<List<UserTreeDto>> getLowerLevelBySharedUid(@PathVariable("userId") String userId) {
        List<UserTreeDto> lsit1=new ArrayList<>();
        List<User> lsit0=new ArrayList<>();

        //根用户
        User user = userService.getById(userId);
        lsit0.add(user);

        //下1级
        List<User> list = userService.lambdaQuery().eq(User::getSharedUid, user.getUserId()).list();
        lsit0.addAll(list);

        //下2级
        List<String> collect = list.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        if(collect.isEmpty()){
            collect.add("-1");
        }
        List<User> list1 = userService.lambdaQuery().in(User::getSharedUid, collect).list();
        lsit0.addAll(list1);

        //下3级
        List<String> collect1 = list1.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        if(collect1.isEmpty()){
            collect1.add("-1");
        }
        List<User> list2 = userService.lambdaQuery().in(User::getSharedUid, collect1).list();
        lsit0.addAll(list2);


        for(User user1:lsit0){
            UserTreeDto dto=new UserTreeDto();
            dto.setId(user1.getUserId());
            dto.setPid(user1.getSharedUid());
            dto.setName(user1.getNickName());
            dto.setImage_url(user1.getPic());

            lsit1.add(dto);
        }

        Map<String, List<UserTreeDto>> collect2 = lsit1.stream().filter((m) -> !StringUtil.equals(m.getId(), user.getUserId())).collect(Collectors.groupingBy(m -> m.getPid()));
        lsit1.forEach(m -> m.setChildren(collect2.get(m.getId())));


        List<UserTreeDto> collect3 = lsit1.stream().filter((m) -> StringUtil.equals(m.getId(), user.getUserId())).collect(Collectors.toList());

        return ServerResponseEntity.success(collect3);
    }

    /**
     * 查询当前登录用户的一级推荐人的数量(一级分销功能接口)
     * @return
     */
    @GetMapping("/getLevel1SharedPeopleNumber")
    public ServerResponseEntity<Map<String,Object>> getLevel1SharedPeopleNumber(String userId) {
        //查看直推人数
        Long count = userService.lambdaQuery().eq(User::getSharedUid, userId).count();
        //查看以下所有推荐人
        List<User>  list0=userService.getLowerLevelBySharedUid(userId,new ArrayList<>());

        Map<String,Object> rmap=new HashMap<>();
        rmap.put("directPushNumber",count);
        rmap.put("lowerLevelNumber",list0.size());
        return ServerResponseEntity.success(rmap);
    }

    /**
     * 普通会员升级为团长(一级分销功能接口)
     * @return
     */
    @PostMapping("/setUserLevel")
    public ServerResponseEntity<Boolean> setUserLevel(String teamName,String userId,String userLevel) {
        if(StringUtil.isBlank(userId) || StringUtil.isBlank(userLevel)){
            return ServerResponseEntity.showFailMsg("参数 userId,userLevel 不能为空");
        }

        if(StringUtil.equals(userLevel,"0")){
            //设置为普通会员
            User byId = userService.getById(userId);
            if(byId == null){
                return ServerResponseEntity.showFailMsg("查询用户为空");
            }
            if(byId.getUserLevel() == null){
                User user=new User();
                user.setUserId(userId);
                user.setUserLevel(0);//普通会员
                userService.updateById(user);

                //设置过期时间为一个月后,如果时间内无新订单,无新推荐用户,用户等级设置为无
                DateTime offset = DateUtil.offset(new Date(), DateField.MONTH, 1);
                userService.lambdaUpdate().set(User::getUserLevelExpireDate,offset).eq(User::getUserId,userId).update();
            }else if(byId.getUserLevel() == 0){
                //已经是普通会员,不做任何操作
            }else if(byId.getUserLevel() == 1){
                //从团长降级为普通会员

                User user=new User();
                user.setUserId(userId);
                user.setUserLevel(0);//普通会员
                userService.updateById(user);
                //清空自己已经推荐的用户
                userService.lambdaUpdate().set(User::getSharedUid,null).eq(User::getSharedUid,userId).update();

                //清空团队名称
                userService.lambdaUpdate().set(User::getTeamName,null).eq(User::getUserId,userId).update();
            }
        }else if (StringUtil.equals(userLevel,"1")){
            //设置为团长
            if(StringUtil.isBlank(teamName)){
                return ServerResponseEntity.showFailMsg("参数 teamName 不能为空");
            }

            Long count = userService.lambdaQuery().eq(User::getSharedUid, userId).count();
            if(count < 300){
                //return ServerResponseEntity.showFailMsg("下级人数不足 300 不能升级团长");
            }

            Long count1 = userService.lambdaQuery().eq(User::getTeamName, teamName).count();
            if(count1 > 0){
                return ServerResponseEntity.showFailMsg("参数 teamName 已被占用,请更换后重试");
            }

            User user=new User();
            user.setUserId(userId);
            user.setSharedUid("");//升级后再最顶级,无推荐人
            user.setUserLevel(1);//团长
            user.setTeamName(teamName);

            userService.updateById(user);

            //设置为NULL
            userService.lambdaUpdate().set(User::getSharedUid,null).eq(User::getUserId,userId).update();
        }
        return ServerResponseEntity.success(true);
    }
}
